package top.lixunda.ecommerce.server.auth.feign;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import top.lixunda.ecommerce.server.auth.api.entity.dto.PhoneCodeDTO;
import top.lixunda.ecommerce.server.auth.api.entity.cache.CacheAuthCode;
import top.lixunda.ecommerce.server.auth.api.feign.IFeignPhoneAuthCode;
import top.lixunda.ecommerce.server.auth.entity.SmsResult;
import top.lixunda.ecommerce.server.auth.service.ISmsService;
import top.lixunda.ecommerce.server.auth.service.SmsTypesCode;
import top.lixunda.commerce.common.core.exception.InternalApiException;
import top.lixunda.common.validate.XumValid;

import java.time.LocalDateTime;
import java.util.Collections;

/**
 * @author Xumda
 * @version time:2019/11/25 9:39
 * <p>
 * 发送短信验证码的类
 */
@RestController
public class FeignPhoneAuthCodeControllerI implements IFeignPhoneAuthCode {

    private final ISmsService smsService;

    @Autowired
    public FeignPhoneAuthCodeControllerI(ISmsService smsService) {
        this.smsService = smsService;
    }

    @Override
    public CacheAuthCode sendRegisterCode(@XumValid PhoneCodeDTO phoneCodeDTO) {
        SmsResult result = smsService.sendSmsCode(phoneCodeDTO.getCode(), phoneCodeDTO.getPhone(),
                SmsTypesCode.CODE_REGISTER);
        if (!result.isSuccess()) {
            throw new InternalApiException(result.getRespDesc());
        }
        CacheAuthCode codeCache = new CacheAuthCode();
        codeCache.setAccounts(Collections.singletonList(phoneCodeDTO.getPhone()));
        codeCache.setAction(CacheAuthCode.ACTION_REGISTER);
        LocalDateTime time = LocalDateTime.now();
        codeCache.setTime(time);
        codeCache.setLateTime(time.plusMinutes(5));
        codeCache.setType(CacheAuthCode.TYPE_PHONE);
        return codeCache;
    }
}
